<?php


namespace app\controller\admin;


use app\BaseController;
use app\common\OrderStatus;
use app\models\goods\CategoryModel;
use app\models\goods\ExchangeOderModel;
use app\models\goods\GoodsModel;
use app\models\goods\GoodsSkuModel;
use app\models\goods\ProductModel;
use app\models\user\UserModel;
use app\services\user\TechnicianService;
use app\validate\GoodsValidate;
use think\facade\Db;

class GoodsController extends BaseAdminController
{
    function setSearch()
    {
        return [
            'like' => ['name'],
            '=' => ['status'],
        ];
    }

    function setSort()
    {
        return [
            'inviter_name' => 'inviter',
            'level_name' => 'level',
        ];
    }

    /**
     * 获取商品列表
     * @return \think\response\Json
     */
    public function getList()
    {
        try {
            $userinfo = $this->request->userInfo;

            $where = $this->searchWhere;
            $orderBy = $this->orderBy;
            $sort = $this->sort;
            if($userinfo['role_id'] == 3){
                $shop_id = intval($userinfo['shop_id']);
                $where[] = ['shop_id','=',$shop_id];
            }
            $list = GoodsModel::where($where)
                ->order($orderBy, $sort)
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $v['goods_sku'] = GoodsSkuModel::field('id,name,market_price,sell_price,stock')
                    ->where('goods_id', $v['id'])
                    ->where('is_del', 0)
                    ->select();
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 添加，编辑
     * @return \think\response\Json
     */
    public function add()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            validate(GoodsValidate::class)->scene('add')->check($data);

            $model = new GoodsModel();
            $userinfo = $this->request->userInfo;
            $data['admin_id'] = $userinfo['id'];
            $data['shop_id']= intval($userinfo['shop_id']);
            $a = $model->save($data);
            $goods_id = $model->getLastInsID();

            $totalStock = 0;
            $skuArr = $data['goods_sku'];
            foreach ($skuArr as &$value) {
                //$value['goods_id'] = $model->id;
                $value['goods_id'] = $goods_id;
                $totalStock += $value['stock'];
            }
            $skuModel = new GoodsSkuModel();
            $skuModel->saveAll($skuArr);

            GoodsModel::update(['stock' => $totalStock], ['id' => $goods_id]);

            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    public function edit()
    {
        Db::startTrans();
        try {
            $data = $this->request->except(['create_time', 'update_time']);
            validate(GoodsValidate::class)->scene('edit')->check($data);

            GoodsSkuModel::update(['is_del' => 1], ['goods_id' => $data['id']]);
            $skuArr = $data['goods_sku'];
            $totalStock = 0;
            foreach ($skuArr as &$value) {
                $skuId = $value['id'] ?? 0;
                if ($skuId) {
                    $value['is_del'] = 0;
                    GoodsSkuModel::update($value);
                } else {
                    $value['goods_id'] = $data['id'];
                    $skuModel = new GoodsSkuModel();
                    $skuModel->save($value);
                }
                $totalStock += $value['stock'];
            }

            $model = GoodsModel::find($data['id']);
            if (!$model) {
                throw new \Exception('商品不存在');
            }
            $data['stock'] = $totalStock;
            $model->save($data);

            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    public function del()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id');
            $status = $this->request->param('status');
            $model = GoodsModel::find($id);
            if (!$model) {
                throw new \Exception("非法请求");
            }
            if ($status == 2) {
                GoodsModel::destroy($id);
            } else {
                $model->status = 2;
                $model->save();
            }
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollBack();
            return $this->error($exception->getMessage());
        }
    }

    public function getCategoryArr()
    {
        try {
            $list = CategoryModel::where('status', 0)
                //->where('pid', 0)
                ->field('id,title,pid')
                ->order('pid asc,sort asc')
                ->select()
                ->toArray();

            $treeAry = getTree(buildTree($list));


            //$treeAry = array_reverse($treeAry);
            return $this->success($treeAry);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function status()
    {
        Db::startTrans();
        try {
            $idArr = $this->request->param('id');
            $status = $this->request->param('status');
            foreach ($idArr as $id) {
                $model = GoodsModel::find($id);
                if (!$model) {
                    throw new \Exception("非法请求");
                }
                $model->status = $status;
                $model->save();
            }
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }
}